package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.log.LogAnno;
import com.itheima.pojo.*;
import com.itheima.service.MenuService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Reference
    MenuService menuService;


    @LogAnno("查询菜单（受限用户权限）")
    @RequestMapping("/getMenu")
    @PreAuthorize("hasAnyAuthority('MENU_QUERY')")
    public Result getMenu() {
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
        List<Menu> menuList = menuService.getMenuByUserName(username);
        return Result.success("", menuList);
    }


    @LogAnno("新增菜单")
    @RequestMapping("/add")
    @PreAuthorize("hasAnyAuthority('MENU_ADD')")
    public Result add(@RequestBody Menu menu) {
        try {
            menuService.add(menu);
            return new Result(true, "新增菜单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "新增菜单失败");
        }
    }


    @LogAnno("编辑菜单")
    @RequestMapping("/edit")
    @PreAuthorize("hasAnyAuthority('MENU_EDIT')")
    public Result edit(@RequestBody Menu menu) {
        try {
            menuService.edit(menu);
            return new Result(true, "编辑菜单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑菜单失败");
        }
    }


    @LogAnno("查询所有菜单")
    @RequestMapping("/findAll")
    @PreAuthorize("hasAnyAuthority('MENU_QUERY')")
    public PageResult findAll(@RequestBody QueryPageBean queryPageBean) {
        return menuService.findAll(queryPageBean);
    }


    @LogAnno("删除菜单")
    @RequestMapping("/deleteById")
    @PreAuthorize("hasAnyAuthority('MENU_DELETE')")
    public Result deleteById(int id) {
        try {
            menuService.deleteById(id);
            return new Result(true, "删除菜单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除菜单失败");
        }
    }


    @LogAnno("回显菜单")
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('MENU_QUERY')")
    public Result findById(int id) {
        try {
            Menu menu =  menuService.findById(id);
            return new Result(true, "回显菜单成功",menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "回显菜单失败");
        }
    }

}
